package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.entity.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.entity.BaseAttrInfo;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author 10574
* @description 针对表【base_attr_info(属性表)】的数据库操作Service实现
* @createDate 2022-11-29 17:33:22
*/
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo>
    implements BaseAttrInfoService{

    @Resource
    BaseAttrValueService baseAttrValueService;

    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseMapper.attrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //存入数据库
        boolean save = save(baseAttrInfo);
        //获取id
        Long id = baseAttrInfo.getId();
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            baseAttrValue.setAttrId(id);
        }
        //批量插入base_Attr_Value数据库
        baseAttrValueService.saveBatch(attrValueList);
    }

    @Override
    public void updateAttrInfo(BaseAttrInfo baseAttrInfo) {
        //修改Base_Attr_Info
        this.updateById(baseAttrInfo);

        //修改Base_Attr_Value
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //那些是删除
        List<Long> ids =new ArrayList<>();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            if(baseAttrValue.getId()!=null){
                ids.add(baseAttrValue.getId());
            }
        }
        if(ids.size()>0){
            baseAttrValueService.lambdaUpdate()
                    .eq(BaseAttrValue::getAttrId,baseAttrInfo.getId())
                    .notIn(BaseAttrValue::getId,ids)
                    .remove();
        }else {
            baseAttrValueService.lambdaUpdate()
                    .eq(BaseAttrValue::getAttrId,baseAttrInfo.getId())
                    .remove();
        }

        for (BaseAttrValue baseAttrValue : attrValueList) {
            if(baseAttrValue.getId()==null){
                //那些是新增
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueService.save(baseAttrValue);
            }else {
                //那些是修改
                baseAttrValueService.updateById(baseAttrValue);
            }
        }
    }
}




